package com.kifas.controller;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.kifas.entity.JenisBarangEntity;
import com.kifas.model.xml.JenisBarangModel;
import com.kifas.model.xml.PersistStatus;
import com.kifas.service.EntityServiceManager;

@Component
@Scope("prototype")
@Path("/JenisBarangs")
public class JenisBarangController {

	private static Logger log = Logger.getLogger(JenisBarangController.class);

	@Context
	UriInfo uriInfo;

	@Autowired
	private EntityServiceManager entityManager;

	@GET
	@Produces(MediaType.TEXT_XML)
	public List<JenisBarangModel> getJenisBarangs() {
		List<JenisBarangEntity> jenisBarangs = entityManager.getJenisBarangs();
		return transformList(jenisBarangs);
	}

	@POST
	@Produces(MediaType.APPLICATION_XML)
	@Consumes(MediaType.APPLICATION_XML)
	public PersistStatus insert(JAXBElement<JenisBarangModel> xml) {
		JenisBarangModel model = xml.getValue();
		JenisBarangEntity jenisBarang = new JenisBarangEntity(null, model.getJenis());
		try {
			entityManager.persist(jenisBarang);
		} catch (Exception e) {
			log.error("can not persist jenis barang entity", e);
			return new PersistStatus("JenisBarangEntity", "failed", "can not persist jenis barang entity");
		}
		return new PersistStatus("JenisBarangEntity", "success");
	}

	@PUT
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public PersistStatus update(JAXBElement<JenisBarangModel> xml) {
		JenisBarangModel model = xml.getValue();
		JenisBarangEntity jenisBarang = new JenisBarangEntity(model.getIdJenisBarang(), model.getJenis());
		try {
			entityManager.update(jenisBarang);
		} catch (Exception e) {
			log.error("can not update jenis barang entity", e);
			return new PersistStatus("JenisBarangEntity", "failed", "can not update jenis barang entity");
		}
		return new PersistStatus("JenisBarangEntity", "success");
	}

	private JenisBarangModel transform(JenisBarangEntity jenisBarang) {
		return new JenisBarangModel(jenisBarang.getIdJenisBarang(), jenisBarang.getJenis(), jenisBarang.getCreatedBy());
	}

	private List<JenisBarangModel> transformList(List<JenisBarangEntity> jenisBarangs) {
		List<JenisBarangModel> jenisBarangEntities = new ArrayList<JenisBarangModel>();
		for (JenisBarangEntity jenisBarang : jenisBarangs) {
			jenisBarangEntities.add(transform(jenisBarang));
		}
		return jenisBarangEntities;

	}
}
